package com.mrobuy.jdvc.controller;

import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.Result;
import com.mrobuy.jdvc.dao.*;
import com.mrobuy.jdvc.entity.*;
import com.mrobuy.jdvc.service.ItemPropService;
import com.mrobuy.jdvc.service.ShelvesService;
import com.mrobuy.util.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class ProductController {

	@Autowired
	private VCProductDao vcProductDao;

	@Autowired
	private VCItemDao vcItemDao;

	@Autowired
	private TaskDao taskDao;

	@Autowired
	private VCProductCreateDao vcProductCreateDao;

	@Autowired
	private ShelvesService shelvesService;

	@Autowired
	private VCCateSalePropDao vcCateSalePropDao;

	@Autowired
	private ItemPropService itemPropService;


	@Autowired
	private VCBrandDao vcBrandDao;

	@Autowired
	private VCCategotyDao vcCategotyDao;


	@RequestMapping("/taskproduct/{taskid}")
	public String taskproduct(@PathVariable String taskid, Model model) {

		VCProductCreateTask task = vcProductCreateDao.load(taskid);
		model.addAttribute("task", task);


		Task condition = new Task();
		condition.setStatus(Task.Status.SUCCESS);
		condition.setType("MYMRO");
		Pagination pagination = taskDao.load(0, Integer.MAX_VALUE, condition);


		model.addAttribute("tasks", pagination.getData());

		return "taskproduct";
	}


	@RequestMapping("/taskproduct/query")
	@ResponseBody
	public Object query(HttpServletRequest request, VCProduct condition) {

		int start = ServletRequestUtils.getIntParameter(request, "start", 1);
		int length = ServletRequestUtils.getIntParameter(request, "length", 10);

		int draw = ServletRequestUtils.getIntParameter(request, "draw", 1);


		Pagination pagination = vcProductDao.load(start, length, condition);

		//int offset = page*pagesize - pagesize;
		pagination.setDraw(draw);

		return pagination;
	}


	@RequestMapping("/taskproduct/skuimport")
	@ResponseBody
	public Result skuimport(HttpServletRequest request, String taskid, String fromid) {

		Result result = new Result();
		if ( taskid==null || taskid.trim().length()==0 ) {
			result.setSuccess(false);
			result.setMsg("参数[taskid]不能为空");
			return result;
		}

		if ( fromid==null || fromid.trim().length()==0 ) {
			result.setSuccess(false);
			result.setMsg("参数[fromid]不能为空");
			return result;

		}

		result = shelvesService.skuimport(taskid, fromid);

		return result;
	}

	@RequestMapping("/taskproduct/shelves")
	@ResponseBody
	public Result shelves(@RequestParam(value = "ids[]") String[] ids) {

		Result result = new Result(true);
		try {
			shelvesService.shelves(ids);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMsg("上架异常: " + e.getMessage());
		}

		return result;
	}




	@RequestMapping(value = "/taskproduct/subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
	@ResponseBody
	public SseEmitter push(String id) throws Exception {


		return shelvesService.buildSseEmitter(id);

	}


	/**
	 * 商品详情
	 */
	@RequestMapping("/productdetail/{id}")
	public String detail(@PathVariable String id, Model model) {


		VCProduct product = vcProductDao.load(id);

		if ( product==null ) {
			product = new VCProduct();
		}

		model.addAttribute("product", product);


		List<VCItem> items = vcItemDao.load(product.getOriginalCode());
		model.addAttribute("items", items);



		List<VCCategorySaleProp> saleProps = vcCateSalePropDao.load(product.getCid1());
		model.addAttribute("saleProps", saleProps);


		model.addAttribute("dim1name",  "属性1");
		model.addAttribute("dim2name",  "属性2");

		for (VCCategorySaleProp saleProp : saleProps) {
			model.addAttribute("dim" + saleProp.getDim() + "name",  saleProp.getName());
		}



		// 规格属性
		List<VCItemPropValue> _propValues = itemPropService.loadPropValues(product, null);
		model.addAttribute("props", _propValues);


		// 扩展属性
		List<VCItemExtPropValue> _extPropValues = itemPropService.loadExtPropValues(product,null);
		model.addAttribute("extProps", _extPropValues);

		// 品牌
		model.addAttribute("brands", vcBrandDao.list());

		// 类目
		model.addAttribute("categories", vcCategotyDao.list());


		return "detail";
	}

	/**
	 * 商品详情更新
	 */
	@RequestMapping("/productdetail/update")
	@ResponseBody
	public Result update(HttpServletRequest request, @RequestBody Params params) {

		VCProduct product = params.getProduct();


		Map<String, String> props = params.getProps();

		if (props!=null && props.size() > 0 ) {
			itemPropService.updtaeProps(product, props);
		}

		if (props!=null && props.size() > 0 ) {
			itemPropService.updtaeExtProps(product, props);
		}

		VCCategory category = vcCategotyDao.load(product.getCid1());
		if ( category!=null ) {
			product.setCidName1(category.getName());
		}

		VCBrand brand = vcBrandDao.load(product.getBrandid());
		if ( brand!=null ) {
			product.setBrandName(brand.getName());
		}

		vcProductDao.update(product, false);

		for (VCItem vcItem : params.getItems()) {
			if ( brand!=null && StringUtils.isNotBlank(brand.getName())) {
				String brandName = brand.getName();
				if ( !vcItem.getSkuName().contains(brandName) ) {
					vcItem.setSkuName(brandName + " " + vcItem.getSkuName());
				}
			}
			vcItemDao.update(vcItem, false);
		}

		return new Result(true);
	}


	static class Params {

		private VCProduct product;

		private List<VCItem> items;

		private Map<String, String> props;

		public VCProduct getProduct() {
			return product;
		}

		public void setProduct(VCProduct product) {
			this.product = product;
		}

		public List<VCItem> getItems() {
			if ( items==null ) {
				return Collections.EMPTY_LIST;
			}
			return items;
		}

		public void setItems(List<VCItem> items) {
			this.items = items;
		}

		public Map<String, String> getProps() {
			return props;
		}

		public void setProps(Map<String, String> props) {
			this.props = props;
		}
	}




}
